package com.java.oauth.service.impl;

import com.java.oauth.service.UserLoginService;
import com.java.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private LoadBalancerClient loadBalancerClient;

	// 客户端id
	@Value("${auth.clientId}")
	private String clientId;
	// 客户端密码
	@Value("${auth.clientSecret}")
	private String clientSecret;
	// 微服务名称
	@Value("${spring.application.name}")
	private String appName;

	// 定义授权方式(密码授权)
	private static final String GRANT_TYPE = "password";


	/**
	 * 授权操作:发送请求获得token
	 */
	@Override
	public AuthToken login(String username, String password) {
		// 获取请求的url
		ServiceInstance serviceInstance = loadBalancerClient.choose(appName);
		String uri = serviceInstance.getUri().toString();
		String url = uri + "/oauth/token";
		// 请求体
		MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
		body.add("grant_type", GRANT_TYPE); // 密码模式(授权方式)
		body.add("username", username);
		body.add("password", password);
		// 请求头
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		byte[] encode = Base64.getEncoder().encode((clientId + ":" + clientSecret).getBytes());
		String encodeMsg = null;
		try {
			encodeMsg = new String(encode, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		headers.add("Authorization", "Basic " + encodeMsg);

		HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(body, headers);
		// 发请求arg01: 请求的url arg02:请求的方式 arg03：请求的体(数据) arg04:响应的结果类型
		// 将请求信息装换成map集合然后封装到token对象中
/*		ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
		Map map = responseEntity.getBody();
		// 将令牌信息封装到AuthToken中
		AuthToken authToken = new AuthToken();
		// 生成的令牌
		authToken.setAccessToken(map.get("access_token").toString());
		// 刷新的令牌
		authToken.setRefreshToken(map.get("refresh_token").toString());
		// 短令牌
		authToken.setJti(map.get("jti").toString());
		return authToken;*/

		ResponseEntity<AuthToken> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, AuthToken.class);
		return responseEntity.getBody();
	}
}
